import 'package:app/api/account/index.dart';
import 'package:app/api/version/index.dart';
import 'package:app/page/home/index.dart';
import 'package:app/page/home/upgrade.dart';
import 'package:app/page/login/index.dart';
import 'package:app/util/SecureStorage.dart';
import 'package:app/util/StringUtils.dart';
import 'package:app/util/WebSocketInheritedWidget.dart';
import 'package:app/util/WebSocketManager.dart';
import 'package:flutter/material.dart';
import 'package:package_info/package_info.dart';

class Interceptor extends StatefulWidget{
  const Interceptor({super.key});

  @override
  State<StatefulWidget> createState()  => _InterceptorState();
}


class _InterceptorState extends State<Interceptor>{

  late Widget page = Container();

  late WebsocketManager _socket;

  @override
  void initState() {
    super.initState();
    checkUpgrade();
    // checkToken();
  }

  /// 检查升级
  void checkUpgrade() async{
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    int versionCode = int.parse(packageInfo.buildNumber);
    VersionApi.of(context).maxVersion().then((res){
      if(StringUtils.isNotNull(res) && StringUtils.isNotNull(res.data)){
        int maxVersionCode = int.parse(res.data['data']['versionCode']);
        print(res.data);
        if(maxVersionCode > versionCode){
          setState(() => page = Upgrade(
            version: res.data['data']['versionName'],
            context: res.data['data']['versionContext'],
            serviceUrl: res.data['data']['versionPath'],
            fileName: res.data['data']['targetFileName'],
          ));
        }else{
          checkToken();
        }
      }else{
        checkToken();
      }
    });
  }

  /// 检查token
  void checkToken(){
    SecureStorage.of().get("token").then((token){
      if(StringUtils.isNotNull(token)){
        Account.of(context).checkToken(token).then((res){
          if(StringUtils.isNotNull(res) && StringUtils.isNotNull(res.data)
              && res.data['data']['flag']){
            setState(() => page = const Index());
            connectSocket();
          }else{
            setState(() => page = const Login());
          }
        });
      }else{
        setState(() => page = const Login());
      }
    });
  }

  /// 连接socket
  void connectSocket(){
    Account.of(context).userInfo().then((res){
      _socket = WebsocketManager(userId: res.data['data']['userId'], device: "0");
      _socket.connection();
      WebSocketInheritedWidget.of(context)?.socket = _socket;
    });
  }

  void hideKeyBorder() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        body: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: hideKeyBorder,
          child: page,
        )
    );
  }
  
}